package com.jtech.together.view.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.model.AddFriendMessage;
import com.jtech.together.model.event.InChatEvent;
import com.jtech.together.model.event.ReceiveMessageEvent;
import com.jtech.together.mvp.contract.MessageContract;
import com.jtech.together.mvp.presenter.MessagePresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.Bus;
import com.jtech.together.view.activity.ChatActivity;
import com.jtech.together.view.activity.UserProfileActivity;
import com.jtech.together.view.adapter.MessageAdapter;
import com.jtech.together.view.fragment.base.BaseFragment;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.jtech.together.view.weight.dialog.MessageOptionDialog;
import com.jtechlib2.listener.OnItemClickListener;
import com.jtechlib2.listener.OnItemLongClickListener;
import com.jtechlib2.listener.OnItemViewSwipeListener;
import com.jtechlib2.view.JRecyclerView;
import com.jtechlib2.view.RecyclerHolder;
import com.jtechlib2.view.RefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;

/**
 * 消息
 * Created by wuxubaiyang on 2017/5/10.
 */
public class MessageFragment extends BaseFragment implements MessageContract.View, RefreshLayout.OnRefreshListener, OnItemClickListener,
        OnItemLongClickListener, OnItemViewSwipeListener, MessageAdapter.OnMessageListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.refreshlayout_message)
    RefreshLayout refreshLayout;
    @Bind(R.id.jrecyclerview_message)
    JRecyclerView jRecyclerView;
    @Bind(R.id.textview_message_none)
    TextView textViewNone;

    private MessageContract.Presenter presenter;
    private MessageAdapter messageAdapter;

    @Override
    public View createView(LayoutInflater layoutInflater, ViewGroup viewGroup) {
        return layoutInflater.inflate(R.layout.fragment_message, viewGroup, false);
    }

    @Override
    protected void initVariables(Bundle bundle) {
        //上车
        Bus.getOn(this);
        //绑定P类
        presenter = new MessagePresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        //设置layoutmanager
        jRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置适配器
        messageAdapter = new MessageAdapter(getActivity());
        jRecyclerView.setAdapter(messageAdapter);
        //设置下拉刷新监听
        refreshLayout.setOnRefreshListener(this);
        //设置item点击事件
        jRecyclerView.setOnItemClickListener(this);
        //设置item长点击事件
        jRecyclerView.setOnItemLongClickListener(this);
        //设置item滑动删除事件
        jRecyclerView.setSwipeStart(true, this);
        //设置消息监听
        messageAdapter.setOnMessageListener(this);
    }

    @Override
    protected void loadData() {
        //刷新会话
        presenter.loadAllConversation();
    }

    /**
     * 移除一条会话
     *
     * @param position
     */
    private void removeConversation(int position) {
        BmobIMConversation conversation = messageAdapter.getItem(position);
        //移除列表中的数据
        messageAdapter.removeData(position);
        //移除会话
        BmobIM.getInstance().deleteConversation(conversation);
        //设置标题栏
        toolbar.setTitle("我的消息(" + messageAdapter.getItemCount() + ")");
        //是否显示空图标
        textViewNone.setVisibility(messageAdapter.getItemCount() <= 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 接受消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveMessage(ReceiveMessageEvent event) {
        presenter.loadAllConversation();
    }

    /**
     * 进入聊天页面消息
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void inChat(InChatEvent event) {
        presenter.loadAllConversation();
    }
    public static MessageFragment newInstance() {
        Bundle args = new Bundle();
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void loadSuccess(List<BmobIMConversation> conversations) {
        refreshLayout.refreshingComplete();
        if (null != conversations) {
            messageAdapter.setDatas(conversations);
            //设置标题栏
            toolbar.setTitle("我的消息(" + conversations.size() + ")");
            //是否显示空图标
            textViewNone.setVisibility(conversations.size() <= 0 ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void loadFail(String error) {
        refreshLayout.refreshingComplete();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void operateSuccess() {
        Snackbar.make(toolbar, "已接受请求", Snackbar.LENGTH_SHORT).show();
        CustomProgressDialog.dismissProgressDialog();
        presenter.loadAllConversation();
    }

    @Override
    public void operateFail(String error) {
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
        CustomProgressDialog.dismissProgressDialog();
    }

    @Override
    public void onRefresh() {
        presenter.loadAllConversation();
    }

    @Override
    public void onItemClick(RecyclerHolder holder, View view, int position) {
        //获取目标用户id
        String targetId = messageAdapter.getUserId(holder.getAdapterPosition());
        //如果是添加好友的会话则点击跳转到用户详情页面
        if (AddFriendMessage.isAddFriend(messageAdapter.getLastMessage(holder.getAdapterPosition()))) {
            Bundle bundle = new Bundle();
            bundle.putString(UserProfileActivity.KEY_USER_OBJECT_ID, targetId);
            ActivityJump.build(getActivity(), UserProfileActivity.class)
                    .addBundle(bundle)
                    .jump();
        } else {
            BmobIMConversation conversation = messageAdapter.getItem(holder.getAdapterPosition());
            conversation.setUnreadCount(0);
            messageAdapter.notifyItemChanged(position);
            //跳转到聊天页面
            Bundle bundle = new Bundle();
            bundle.putString(ChatActivity.KEY_TARGET_ID, targetId);
            ActivityJump.build(getActivity(), ChatActivity.class)
                    .addBundle(bundle)
                    .jump();
        }
    }

    @Override
    public boolean onItemLongClick(final RecyclerHolder holder, View vie, int position) {
        //弹出操作dialog
        MessageOptionDialog.build(getActivity())
                .setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0://查看好友信息
                                Bundle bundle = new Bundle();
                                bundle.putString(UserProfileActivity.KEY_USER_OBJECT_ID,
                                        messageAdapter.getUserId(holder.getAdapterPosition()));
                                ActivityJump.build(getActivity(), UserProfileActivity.class)
                                        .addBundle(bundle)
                                        .jump();
                                break;
                            case 1://删除消息
                                removeConversation(holder.getAdapterPosition());
                                break;
                        }
                    }
                }).show();
        return true;
    }

    @Override
    public void onItemViewSwipe(RecyclerView.ViewHolder viewHolder, int direction) {
        removeConversation(viewHolder.getAdapterPosition());
    }

    @Override
    public void acceptAddFriend(BmobIMConversation conversation, BmobIMUserInfo userInfo) {
        presenter.acceptAddFriend(conversation, userInfo,
                getResources().getString(R.string.accept_add_friend_message));
        CustomProgressDialog.showProgressDialog(getActivity(), "接收好友请求");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //下车
        Bus.getOff(this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
    }
}